package shs

import (
	"bytes"
	"slices"
	"sort"
)

var _ sort.Interface = (*SortUserRecordByKey)(nil)

type SortUserRecordByKey []Record

func (s SortUserRecordByKey) Len() int {
	return len(s)
}

func compareBytes(a, b []byte) bool {
	return bytes.Compare(a, b) < 0
}

func (s SortUserRecordByKey) Less(i, j int) bool {
	return compareBytes(s[i].Key, s[j].Key)
}

func (s SortUserRecordByKey) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func binarySearchUserRecordsByKey(arr []Record, target []byte) int {
	left, right := 0, len(arr)-1

	for left <= right {
		mid := left + (right-left)/2 // 防止溢出
		if slices.Equal(arr[mid].Key, target) {
			return mid // 找到目标，返回索引
		} else if compareBytes(arr[mid].Key, target) {
			left = mid + 1 // 在右半部分继续搜索
		} else {
			right = mid - 1 // 在左半部分继续搜索
		}
	}

	return -1 // 未找到目标，返回-1
}
